package cn.catsdad.page;

import cn.catsdad.base.page.PageParam;
import cn.catsdad.constant.iConstant.IDateFormat;
import cn.catsdad.util.DateUtil;
import cn.catsdad.util.StringUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.util.*;

/**
 * 用户查询参数
 *
 * @author xuyonglong
 * @version V1.0 2023/4/21
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
public class UserParam extends PageParam {

    private Map<String, Object> paramMap = new HashMap<>();

    /**
     * 关键字查询，用户名、登录名、手机号
     */
    private String key;

    /**
     * 部门id
     */
    private Long departmentId;

    /**
     * 状态查询
     */
    private int status;

    /**
     * 查询开始时间
     */
    private String startTime;

    /**
     * 查询结束时间
     */
    private String endTime;

    /**
     * 部门集合列表，用于支持使用父级查询子级
     */
    private List<Long> allDepartmentIds;

    @Override
    public Map<String, Object> getParamMap() {
        return this.paramMap;
    }

    @Override
    public String getCondition() {
        StringBuilder condition = new StringBuilder(" and u.isDeleted = 0 ");
        if (StringUtil.isNotEmpty(this.key)) {
            condition.append(" and (u.userName like :key or u.loginName like :key or tel like :key) ");
            this.paramMap.put("key", likeQuery(this.key));
        }
        if (this.status != 0) {
            condition.append(" and u.status = :status ");
            this.paramMap.put("status", this.status);
        }
        if (this.departmentId != null) {
            condition.append(" and u.id in (select du.userId from DtoDepartmentUser du where du.departmentId in :departmentId )");
            this.paramMap.put("departmentId", this.allDepartmentIds);
        }
        if (StringUtil.isNotEmpty(this.startTime)) {
            Date date = DateUtil.parseDateFromStr(this.startTime, IDateFormat.YYYY_MM_DD);
            condition.append(" and u.creationTime >= :start");
            this.paramMap.put("start", date);
        }
        if (StringUtil.isNotEmpty(this.endTime)) {
            Date date = DateUtil.parseDateFromStr(this.endTime, IDateFormat.YYYY_MM_DD);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            condition.append(" and u.creationTime <= :end");
            this.paramMap.put("end", calendar.getTime());
        }
        return condition.toString();
    }
}
